package org.jeecg.modules.bobo.wechat.common.util;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * @program: jeecg-boot-parent
 * @description:
 * @author: 三千霜
 * @create: 2020-04-22 17:18
 */

public class WxUtils {

    @Autowired
    private  static WxMpService wxMpService;
//    @Autowired
//    private  static IWeixinMessageTemplateService weixinMessageTemplateService;
//    @Autowired
//    private  static IWeixinMessageTemplateDataService weixinMessageTemplateDataService;

    /**
     * 通过身份证号码获取出生日期、性别、年龄
     * @param certificateNo
     * @return 返回的出生日期格式：1990-01-01   性别格式：F-女，M-男
     */
    public static Map<String, String> getBirAgeSex(String certificateNo) {
        String birthday = "";
        String age = "";
        String sexCode = "";

        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = certificateNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (int x = 0; x < number.length; x++) {
                if (!flag) {
                    return new HashMap<String, String>();
                }
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag) {
                    return new HashMap<String, String>();
                }
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && certificateNo.length() == 15) {
            birthday = "19" + certificateNo.substring(6, 8) + "-"
                    + certificateNo.substring(8, 10) + "-"
                    + certificateNo.substring(10, 12);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
        } else if (flag && certificateNo.length() == 18) {
            birthday = certificateNo.substring(6, 10) + "-"
                    + certificateNo.substring(10, 12) + "-"
                    + certificateNo.substring(12, 14);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("birthday", birthday);
        map.put("age", age);
        map.put("sexCode", sexCode);
        return map;
    }
    /**
     * 获取当前时间的时间戳
     * @return
     */
    public static String getTimeInMillis() {
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        return timeInMillis+"";
    }
    /**
     * 获取位数为7位的随机数
     * @return
     */
    public static synchronized String getRandom() {
        Random random = new Random();
        int nextInt = random.nextInt(10000000);
        nextInt=nextInt+1000000;
        String str=nextInt+"";
        return str;
    }
    public static synchronized String getRandom(int x) {
        Random random = new Random();
        Integer ds=1;
        int i=0;
        while (i<x-1){
            ds*=10;
            i++;
        }
        int nextInt = random.nextInt(ds);
        nextInt=nextInt+ds;
        String str=nextInt+"";
        return str;
    }

    public static String getTimeYearMonthDay() {
        Calendar c = Calendar.getInstance();
        int year=c.get(Calendar.YEAR);
        int month=c.get(Calendar.MONTH)+1;
        int day=c.get(Calendar.DAY_OF_MONTH);
        int hh=c.get(Calendar.HOUR_OF_DAY);
        int mi=c.get(Calendar.MINUTE);
        int ss=c.get(Calendar.SECOND);
        System.out.println(year+" "+month+" "+day+" "+hh+" "+mi+" "+ss);
        return null;
    }

    /**
     * 输入日期格式，返回格式内的内容，输入格式以-分隔
     * @param dateFormat
     * @return
     */
    public static String getTimeYearMonthDay(String dateFormat) {
        String[] strNow = new SimpleDateFormat(dateFormat).format(new Date()).toString().split("-");
        String str="";
        for (String string : strNow) {
            str=str+string;
        }
        return str;
    }
    /**
     * 获得20位的主键值，主键值的格式是13位的当前时间戳加7位的随机数
     * @return
     */
    public static synchronized String getPrimaryKey() {
        return getTimeInMillis()+getRandom();
    }
    public static synchronized String getPrimaryKey(int x) {
        return getTimeInMillis()+getRandom(x);
    }

    public static  String getWeekName(ZonedDateTime plus){
        String[][] strArray = {{"MONDAY", "一"}, {"TUESDAY", "二"}, {"WEDNESDAY", "三"}, {"THURSDAY", "四"}, {"FRIDAY", "五"}, {"SATURDAY", "六"}, {"SUNDAY", "日"}};
        String k = String.valueOf(plus.getDayOfWeek());
        //获取行数
        for (int i = 0; i < strArray.length; i++) {
            if (k.toUpperCase().equals(strArray[i][0])) {
                k = strArray[i][1];
                break;
            }
        }
        return k;
    }

    /**
     * 针对微信支付生成商户订单号，为了避免微信商户订单号重复（下单单位支付），
     *
     * @return
     */
    public static synchronized String generateOrderSN(String prefix,String suffix) {
        StringBuffer orderSNBuffer = new StringBuffer();
        orderSNBuffer.append(prefix);
        orderSNBuffer.append(getTimeInMillis());
        orderSNBuffer.append(suffix);
        return orderSNBuffer.toString();
    }
    public static String generateOrderSN(String prefix) {
        return generateOrderSN(prefix,"");
    }

    public static String generateOrderSN(String prefix,Boolean isRandom) {
        if (isRandom){
            return generateOrderSN(prefix,getRandom());
        }else{
            return generateOrderSN(prefix,"");
        }
    }

    public static <T> Map<String,String>  getFieldByName(T t){
        //现在要获取字段day02b的值
        Field[] declaredFields = t.getClass().getDeclaredFields();
        Map<String,String> map=new HashMap<>();
        try {
            for (Field field : declaredFields) {
                //字段名称
                String name = field.getName();
                field.setAccessible(true);
                String value =String.valueOf(field.get(t));
                map.put(name, value);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }
    //微信模板消息发送
//    public static String sendTemplateMsg(String openid, String templateid,Map<String,String> fieldByName) throws WxErrorException {
//        //获取模板数据
//        WeixinMessageTemplate weixinMessageTemplate=weixinMessageTemplateService.getById(templateid);
//        List<WeixinMessageTemplateData> weixinMessageTemplateDatas = weixinMessageTemplateDataService.selectByMainId(weixinMessageTemplate.getTemplateId());
//        //推送模板
//        WxMpTemplateMessage orderPaySuccessTemplate = WxMpTemplateMessage.builder().build();
//        orderPaySuccessTemplate.setToUser(openid);
//        orderPaySuccessTemplate.setTemplateId(weixinMessageTemplate.getTemplateId());
//        if (StringUtils.isNotBlank(weixinMessageTemplate.getUrl())){
//            orderPaySuccessTemplate.setUrl(weixinMessageTemplate.getUrl());
//        }
//        WxMpTemplateData firstData =null;
//        for (WeixinMessageTemplateData wd :
//                weixinMessageTemplateDatas) {
//            firstData=new WxMpTemplateData(wd.getName(), fieldByName.get(wd.getName()), wd.getColor());
//            orderPaySuccessTemplate.addData(firstData);
//        }
//        String sendTemplateMsg ="";
//        sendTemplateMsg =  wxMpService.getTemplateMsgService().sendTemplateMsg(orderPaySuccessTemplate);
//
//        return sendTemplateMsg;
//
//    }
}
